<template>
  <div class="comp-column-info">
    <div class="title-box">
      <div class="column-item-title">
        <span
          class="title-label"
          @click="
            () => {
              if (!(column.isNumber && !column.isDate)) {
                activeColumn(column)
              }
            }
          "
          >{{ column.label }}</span
        >
        <span
          class="ant-checkbox"
          :class="{
            'ant-checkbox-disabled': column.isNumber && !column.isDate,
            'ant-checkbox-checked': fieldList.find(
              (item) => item.label === column.label
            ),
          }"
          @click="
            () => {
              if (!(column.isNumber && !column.isDate)) {
                toggleField(column)
              }
            }
          "
        >
          <span class="ant-checkbox-inner"></span>
        </span>
      </div>
    </div>
    <div class="chart-box">
      <chart
        v-if="chartConfig"
        chart-type="scalableBarChart"
        :config="chartConfig"
      >
      </chart>
    </div>
  </div>
</template>
<script lang="ts">
import Vue from 'vue'
import { apiGetColumnStat } from '@/api/data-clean'
import { ColumnStat } from '@/components/studio/data/node-edit-panel/interface'
import Chart from '../chart/chart.vue'
import KV from '../form/kv'

export default Vue.extend({
  components: {
    Chart,
  },
  props: {
    dataId: {
      type: [String, Number],
      default() {
        return ''
      },
    },
    tableName: {
      type: String,
      default() {
        return ''
      },
    },
    fieldList: {
      type: Array,
      default() {
        return []
      },
    },
    column: {
      type: Object,
      default() {
        return {}
      },
    },
  },
  data() {
    return {
      chartConfig: null,
      columnStat: null,
      chartHeight: 240,
      columnFilters: [],
      requestParams: {
        curPage: 1,
        pageSize: 50,
        sortType: 1,
        sortVal: 'ASC',
      },
    }
  },
  methods: {
    statMode() {
      return ['text', 'varchar'].includes(this.column.type)
        ? 'detail'
        : 'binned'
    },
    init() {
      const that = this as any
      that.getNewColumnStat().then((response: any) => {
        that.columnStat = response
        that.$nextTick(() => {
          that.chartConfig = that.getChartConfig(that.columnStat)
        })
      })
    },

    pageCountToChartValue(pageCount: ColumnStat['pageCount']) {
      const { data, curPage, pageSize } = pageCount || {}
      if (!data) {
        return null
      }
      return data.map((d, i) => ({
        label: d.column,
        index: pageSize! * (curPage! - 1) + i,
        yAxisValue: d.column,
        value: [d.count, d.highLight || 0],
      }))
    },

    rangeCountToChartOverview(rangeCount: ColumnStat['rangeCount']) {
      return rangeCount.map((d) => [d.count, d.highLight || 0])
    },

    getChartConfig(columnStat: any) {
      if (!columnStat) {
        return null
      }

      let elementType: string
      let maxValue: number
      let value: { label: any; value: number[] }[]
      let overviewOptions: number[][]
      let barRatio: number = 1

      if (this.statMode() === 'detail') {
        elementType = 'discrete'
        maxValue = columnStat.topColumn.count
        value = this.pageCountToChartValue(columnStat.pageCount) || []
        overviewOptions = this.rangeCountToChartOverview(columnStat.rangeCount)
        const rangeCountElement = columnStat.rangeCount[0]!
        barRatio = rangeCountElement.up - rangeCountElement?.low
      } else {
        elementType = 'continuous'
        maxValue = Math.max(...columnStat.rangeCount.map((d: any) => d.count))
        value = columnStat.rangeCount.map((d: any, i: number) => ({
          label: `${d.low} - ${d.up}`,
          index: i,
          yAxisValue: d.low,
          value: [d.count, d.highLight || 0],
          low: d.low,
          up: d.up,
        }))
        overviewOptions = []
      }

      return {
        maxValue,
        totalValue: columnStat.total,
        elementType,
        radio: barRatio,
        value,
        overviewOptions,
        size: [180, this.chartHeight],
        barHeight: elementType === 'continuous' ? 10 : 20,
        barGap: 2,
        subBarGap: 0,
        overviewBarHeight: 2,
        overviewSubBarGap: 0,
        padding: [12, 8, 12, 4],
        tooltipIsShow: true,
        barColor: '#E9E9E9',
        subBarColor: '#B6BAF1',
        overviewFocusBarStrokeColor: '#D8D8D8',
        yAxisFontColor: '#373B52',
        yAxisLineColor: '#ccc',
      }
    },
    columnStatParams(): KV {
      const that = this as any
      return {
        ...that.requestParams,
        table: that.tableName.split('.')[1],
        name: that.column.value,
        type: that.column.type_,
        mode: that.column.isNumber ? 2 : 1, // that.statMode() === 'detail' ? 1 : 2,
        filter: that.columnFilters,
        // dataId: that.dataId,
        // taskId: that.selectNode.id,
      }
    },
    getNewColumnStat(): Promise<ColumnStat | null> {
      return this.getColumnStat(this.columnStatParams())
    },
    async getColumnStat(data: any): Promise<ColumnStat | null> {
      if (!this.column) {
        return null
      }
      const response = await apiGetColumnStat({ data })
      if (response.status === 200 && response.data.success) {
        return response.data.result
      }
      return null
    },
    activeColumn(column: any) {
      this.$emit('activecolumn', column)
    },
    toggleField(column: any) {
      this.$emit('togglefield', column)
    },
  },
})
</script>

<style lang="less" scoped>
.comp-column-info {
  background: #fff;
  border: 1px solid rgba(239, 233, 255, 0.59);
  border-radius: 8px;
  box-shadow: 0 0 4px 0 #f6f4fd;
  height: 400px;
  margin-right: 10px;
  overflow: hidden;
  width: 190px;

  .column-item-title {
    align-content: center;
    color: #5d637e;
    display: flex;
    flex-flow: row nowrap;
    font-size: 14px;
    height: 38px;
    justify-content: space-between;
    letter-spacing: 1px;
    line-height: 14px;
    padding: 14px 12px 4px;
    width: 100%;

    .title-label {
      cursor: pointer;
      width: calc(100% - 20px);
    }

    .ant-checkbox {
      transform: translateY(2px);
    }
  }

  .chart-box {
    height: 300px;
    position: relative;
    width: 100%;
  }
}
</style>
